<template>
  <el-dialog append-to-body title="分配权限" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" :visible.sync="visible" :width="'640px'">
    <el-row :gutter="10" v-loading="loading">
        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
            <el-form :inline="true" size="small" @submit.native.prevent>
                <el-form-item>
                    <el-input size="small" placeholder="请输入权限" v-model.trim="searchName" maxlength="30" clearable @input="filteDepartTree"></el-input>
                </el-form-item>
            </el-form>
            <div class="tree_box">
                <el-tree ref="treeRef" default-expand-all show-checkbox node-key="id" :data="renderPowerTreeData" :filter-node-method="filterNode" :default-checked-keys="checkedKeys" @check="checkOption">
                    <div class="custom-tree-node" slot-scope="{ data }">
                        <span>{{ data.roleName }}</span>
                    </div>
                </el-tree>
            </div>
        </el-col>
        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
            <div>用户<span v-show="name">“{{name}}”</span>将拥有以下权限：</div>
            <div class="tag_box">
                <el-tag size="small" class="tag_item" :closable="!item.disabled" @close="unCheckOption(item.id)" v-for="item in checkedNodes" :key="'tag' + item.id">{{item.roleName}}</el-tag>
            </div>
        </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button :disabled="submitLoading" @click="closeModal()">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="submit()">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { GetRoleAll, GetDepartRoleAll, GetUserById, UpdateUser } from '@/views/user-management/services/index';
export default {
  props: ['visible', 'departId', 'name', 'userType', 'itemId', 'checked'],
  data() {
    return {
      myData: null,
      searchName: '',
      checkedKeys: [],
      checkedNodes: [],
      defaultPowerTreeData: [],
      renderPowerTreeData: [],
      loading: false,
      submitLoading: false
    }
  },
  watch: {
    visible: {
      immediate: true,
      handler(newValue, oldValue) {
        if (!newValue) return;
        this.loading = true;
        if (!this.departId || this.departId == '0') {
          if (this.itemId) {
            this.setData();
            return;
          }
          GetRoleAll({ type: this.userType, proId: 4 })
          .finally(() => this.loading = false)
          .then(data => {
            this.defaultPowerTreeData = data.data.map(item => {
              item.disabled = item.roleStatus == 1;
              return item;
            });
            this.renderPowerTreeData = JSON.parse(JSON.stringify(this.defaultPowerTreeData));

            this.checkedKeys = (this.checked && this.checked.length) ? this.checked : [];
            this.checkedNodes = this.checkedKeys.map(item => this.defaultPowerTreeData.find(fItem => fItem.id == item)).filter(item => item);;
          })
        } else {
          if (this.itemId) {
            this.setData();
            return;
          }
          GetDepartRoleAll({ proId: 4, depId: this.departId })
          .finally(() => this.loading = false)
          .then(data => {
            this.defaultPowerTreeData = data.data.map(item => {
              item.disabled = item.roleStatus == 1;
              return item;
            });
            this.renderPowerTreeData = JSON.parse(JSON.stringify(this.defaultPowerTreeData));
            this.checkedKeys = (this.checked && this.checked.length) ? this.checked : [];
            this.checkedNodes = this.checkedKeys.map(item => this.defaultPowerTreeData.find(fItem => fItem.id == item)).filter(item => item);;
          })
        }
      }
    }
  },
  methods: {
    setData() {
      GetUserById({id: this.itemId})
      .finally(() => this.loading = false)
      .then(data => {
        this.myData = data.data;
        if (data.data.depId && data.data.depId != '0') {
          GetDepartRoleAll({ proId: 4, depId: data.data.depId })
          .then(success => {
            this.defaultPowerTreeData = success.data.map(item => {
              item.disabled = item.roleStatus == 1;
              return item;
            });
            this.renderPowerTreeData = JSON.parse(JSON.stringify(this.defaultPowerTreeData));

            this.checkedKeys = (data.data.roleIds && data.data.roleIds.length) ? data.data.roleIds : [];
            this.checkedNodes = this.checkedKeys.map(item => this.defaultPowerTreeData.find(fItem => fItem.id == item)).filter(item => item);
          })
          return;
        } else {
          GetRoleAll({ type: this.userType, proId: 4 })
          .finally(() => this.loading = false)
          .then(success => {
            this.defaultPowerTreeData = success.data.map(item => {
              item.disabled = item.roleStatus == 1;
              return item;
            });
            this.renderPowerTreeData = JSON.parse(JSON.stringify(this.defaultPowerTreeData));

            this.checkedKeys = (data.data.roleIds && data.data.roleIds.length) ? data.data.roleIds : [];
            this.checkedNodes = this.checkedKeys.map(item => this.defaultPowerTreeData.find(fItem => fItem.id == item)).filter(item => item);
          })
        }
      })
    },
    checkOption(value, nodes) {
      this.checkedNodes = nodes.checkedNodes;
    },
    unCheckOption(id) {
      this.$refs.treeRef.setChecked(id, false, true);

      this.checkedNodes = this.$refs.treeRef.getCheckedNodes();
    },
    filteDepartTree(value) {
      this.$refs.treeRef.filter(value);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.roleName.indexOf(value) !== -1;
    },
    submit() {
      if (this.itemId) {
        const { id, proId, userType, gender, headUrl, name, username, phone, depId, workDescribe, checkStatus } = this.myData;
        const queryData = {
          id, proId, userType, gender, headUrl, name, username, phone, depId, workDescribe, checkStatus,
          roleIds: this.checkedNodes.map(item => item.id)
        };
        UpdateUser(queryData)
          .then(success => {
            this.submitLoading = false;
            if (success.code == 200) {
              this.$message.success('分配权限成功!');
              this.closeModal();
              this.$emit('update', true);
            } else {
              this.$message.error('分配权限失败!');
            }
          })
          .catch(error => {
            this.submitLoading = false;
            this.$message.error(error);
          })
      } else {
        this.$emit('check', this.checkedNodes);
        this.closeModal();
      }
    },
    closeModal() {
      this.$emit('update:visible', false);
      this.searchName = '';
      this.myData = null;
      this.searchName = '';
      this.checkedKeys = [];
      this.checkedNodes = [];
      this.defaultPowerTreeData = [];
      this.renderPowerTreeData = [];
    }
  }
}
</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
::v-deep .el-tree-node__content {
  height: 38px;
}
.tree_box {
    max-height: 480px;
    overflow-x: hidden;
    overflow-y: auto;
    padding: 10px 0;
}

.tag_box {
  margin: 20px -5px 0;

  .tag_item {
    margin: 5px;
  }
}
</style>
